package com.chlp.core.framework.exception;

import com.chlp.core.framework.utils.CommonCurdResultBean;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.ByteArrayOutputStream;

/**
 * 全局异常捕捉处理
 *
 * @author ChenLiPeng
 * @date 2020/4/11 12:46
 */
@ControllerAdvice
public class CustomExceptionHandler {

	/**
	 * 全局异常捕捉处理
	 */
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public CommonCurdResultBean<Object> errorHandler(Exception ex) {
		getThrowableStackInfo(ex);
		return new CommonCurdResultBean<>(false, ex.getMessage());
	}

	/**
	 * 全局捕捉自定义异常（凡是抛出MyException的异常都会走这里）
	 */
	@ResponseBody
	@ExceptionHandler(value = CustomException.class)
	public CommonCurdResultBean<Object> myErrExceptionHandler(CustomException ex) {
		getThrowableStackInfo(ex);
		return new CommonCurdResultBean<>(false, ex.getMessage());
	}

	/**
	 * 堆栈信息打印方法如下
	 */
	public static String getThrowableStackInfo(Throwable e) {
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		e.printStackTrace();
		e.printStackTrace(new java.io.PrintWriter(buf, true));
		String msg = buf.toString();
		try {
			buf.close();
		} catch (Exception t) {
			return e.getMessage();
		}
		return msg;
	}
}
